import React, {PureComponent} from 'react';
import PropTypes from 'prop-types';
import {Row, Col, Form, Button, Divider, Table, message as msg, Modal} from 'antd';
import {PAGE, TABLE, PAGINATION_OPTIONS, FORM_OPTIONS, ROWSELECTION_FIXED_COLUMN_WIDTH} from '../constants';
import TextInput from 'Shared/components/TextInput';
import {conventEnumValueToString, conventSorter} from '../utils';
import {salePlanAssembleMethod} from '../Enum';
import SelectAlert from '../common/SelectAlert';
import {addMonths} from './utils';
import styles from './style.css';
import {getSalePlanOrders} from './api';
const FormItem = Form.Item;
const MultiSelectAlert = SelectAlert.Multi;

class PlanCodePanel extends PureComponent {
    state = {
        isFetching: false,
        data: {},
        message: '',
        pageIndex: PAGE.index,
        pageSize: PAGE.smallSize,
        currentCondition: {},
        keys: [],
        rows: [],
    }
    
    handleTableChange = (pagination, filters, sorter) => {
        const oldCondition = {...this.state.currentCondition};
        if(pagination.current - 1 === oldCondition.pageIndex && pagination.pageSize === oldCondition.pageSize) {
            const sortOptions = conventSorter(sorter);
            const condition = Object.assign({}, oldCondition, sortOptions, {
                pageIndex: pagination.current - 1
            });
            this.onQuery(condition);
            this.setState({
                sortField: sortOptions.sortField,
                isDesc: sortOptions.isDesc
            });
        }
    }

    handleFilterPressEnter = (value, name) => {
        this.setState({[name]: value}, this.onClickSearchBtn);
    }

    onQuery = condition => {
        this.setState({isFetching: true});
        getSalePlanOrders(condition)
            .then(res => {
                if(res.ok)
                    this.setState({
                        isFetching: false,
                        message: '',
                        data: res.data,
                        currentCondition: condition
                    });
                else
                    this.setState({
                        isFetching: false,
                        data: [],
                        message: res.message
                    });
            });
    }

    onClickSearchBtn = () => {
        const condition = {
            brandId: this.props.brandId,
            dealerId: this.props.dealerId,
            materialGroupKDBOMCode: this.props.materialGroupKDBOMCode,
            pageIndex: PAGE.index,
            pageSize: this.state.pageSize,
            sortField: this.state.sortField,
            isDesc: this.state.isDesc
        };
        this.onQuery(condition);
    }

    onPageIndexChange = current => {
        const condition = {...this.state.currentCondition};
        condition.pageIndex = current - 1;
        this.onQuery(condition);
    }

    onPageSizeChange = (current, pageSize) => {
        const condition = {...this.state.currentCondition};
        condition.pageIndex = PAGE.index;
        condition.pageSize = pageSize;
        this.onQuery(condition);
        this.setState({
            pageSize
        });
    }

    onChange = (value, name) => {
        this.setState({[name]: value});
    }
    onChangeRadio = (keys, rows) => {
        this.setState({
            keys,
            rows
        });
    }

    onCloseTag = () => {
        this.setState({
            keys: [],
            rows: []
        });
    }

    onSubmit = () => {
        if(!this.state.rows.length)
            return msg.warn(this.props.intl.formatMessage({
                id: 'PlanCodePanel.validate.PlanCodeTileds',
                defaultMessage: '请选择滚动计划信息'
            }));
        this.props.onSelect(this.state.rows[0]);
    }
    
    render() {
        const {formatMessage} = this.props.intl;
        const {isFetching, data} = this.state;
        const {pageIndex, pageSize} = this.state.currentCondition;
        const n = (data.content && data.content.length !== 0) ? data.content[0].submitMonth : 0;
        const columns = [
            {
                title: formatMessage({
                    id: 'PlanCodePanel.column.planCode',
                    defaultMessage: '计划编号'
                }),
                dataIndex: 'planCode'
            }, {
                title: formatMessage({
                    id: 'PlanCodePanel.column.assembleMethod',
                    defaultMessage: '装配方式'
                }),
                dataIndex: 'assembleMethod',
                render: text => conventEnumValueToString(salePlanAssembleMethod, text)
            }, {
                title: formatMessage({
                    id: 'PlanCodePanel.column.materialGroupKDBOMCode',
                    defaultMessage: '物料组号或KDBOM编号'
                }),
                dataIndex: 'materialGroupKDBOMCode'
            }, {
                title: formatMessage({
                    id: 'PlanCodePanel.column.referenceMaterialGroupKDBOMCode',
                    defaultMessage: '参考物料组号或KDBOM编号'
                }),
                dataIndex: 'referenceMaterialGroupKDBOMCode'
            }, {
                title: formatMessage({
                    id: 'PlanCodePanel.column.modelCode',
                    defaultMessage: '车型代码'
                }),
                dataIndex: 'modelCode'
            },
            {
                title: addMonths(1) + formatMessage({
                    id: 'PlanCodePanel.column.n1Quantity',
                    defaultMessage: '月份数量'
                }),
                dataIndex: 'n1Quantity'
            }, {
                title: addMonths(2) + formatMessage({
                    id: 'PlanCodePanel.column.n2Quantity',
                    defaultMessage: '月份数量'
                }),
                dataIndex: 'n2Quantity'
            }, {
                title: addMonths(3) + formatMessage({
                    id: 'PlanCodePanel.column.n3Quantity',
                    defaultMessage: '月份数量'
                }),
                dataIndex: 'n3Quantity'
            }, {
                title: addMonths(4) + formatMessage({
                    id: 'PlanCodePanel.column.n4Quantity',
                    defaultMessage: '月份数量'
                }),
                dataIndex: 'n4Quantity'
            }, {
                title: addMonths(5) + formatMessage({
                    id: 'PlanCodePanel.column.n5Quantity',
                    defaultMessage: '月份数量'
                }),
                dataIndex: 'n5Quantity'
            }, {
                title: addMonths(6) + formatMessage({
                    id: 'PlanCodePanel.column.n6Quantity',
                    defaultMessage: '月份数量'
                }),
                dataIndex: 'n6Quantity'
            },
            {
                title: formatMessage({
                    id: 'PlanCodePanel.column.marketDepartmentName',
                    defaultMessage: '大区名称'
                }),
                dataIndex: 'marketDepartmentName'
            }, {
                title: formatMessage({
                    id: 'PlanCodePanel.column.country',
                    defaultMessage: '国家'
                }),
                dataIndex: 'country'
            }, {
                title: formatMessage({
                    id: 'PlanCodePanel.column.dealerCode',
                    defaultMessage: '总代编号'
                }),
                dataIndex: 'dealerCode'
            }, {
                title: formatMessage({
                    id: 'PlanCodePanel.column.dealerName',
                    defaultMessage: '总代名称'
                }),
                dataIndex: 'dealerName'
            }, {
                title: formatMessage({
                    id: 'PlanCodePanel.column.submitYear',
                    defaultMessage: '提报年份'
                }),
                dataIndex: 'submitYear'
            }, {
                title: formatMessage({
                    id: 'PlanCodePanel.column.submitMonth',
                    defaultMessage: '提报月份'
                }),
                dataIndex: 'submitMonth',
            }, {
                title: formatMessage({
                    id: 'PlanCodePanel.column.manufacturerName',
                    defaultMessage: '生产工厂名称'
                }),
                dataIndex: 'manufacturerName'
            }
        ];
            

        const pagination = {
            total: data.totalElements,
            current: pageIndex + 1,
            pageSize,
            onShowSizeChange: this.onPageSizeChange,
            onChange: this.onPageIndexChange,
            ...PAGINATION_OPTIONS
        };
        const onRow = record => ({
            onDoubleClick: () => {
                // 双击选中
                this.props.onSelect(record);
            }
        });
        const rowSelection = {
            type: 'radio',
            fixed: true,
            columnWidth: ROWSELECTION_FIXED_COLUMN_WIDTH,
            onChange: this.onChangeRadio,
            selectedRowKeys: this.state.keys,
        };
        const selectRows = this.state.rows.length ? [{
            text: this.state.rows[0].code,
            value: this.state.rows[0].id
        }] : [];
        return (
            <Modal
                title={formatMessage({
                    id: 'PlanCodePanel.show.query',
                    defaultMessage: '滚动计划查询'
                })}
                width="60%"
                maskClosable={false}
                footer={null}
                destroyOnClose={true}
                wrapClassName={styles.dataSelectModal}
                visible={true}
                onCancel={this.props.onCancel}>
                <Row className="form-standard">
                    <Col {...FORM_OPTIONS.col} className={styles['inline-button']}>
                        <Button
                            type="primary"
                            loading={isFetching}
                            onClick={this.onClickSearchBtn}>
                            {formatMessage({
                                id: 'PlanCodePanel.btn.query',
                                defaultMessage: '查询'
                            })}
                        </Button>
                    </Col>
                </Row>
                <Divider className={styles.divider}/>
                <SelectAlert data={selectRows}
                    onConfirm={this.onSubmit}
                    onDelete={this.onCloseTag}/>
                <Table
                    className="white-space-nowrap"
                    rowKey="id"
                    dataSource={data.content}
                    rowClassName={styles.tableCursor}
                    columns={columns}
                    onRow={onRow}
                    loading={isFetching}
                    pagination={pagination}
                    onChange={this.handleTableChange}
                    rowSelection={rowSelection}
                    {...TABLE}/>
            </Modal >
        );
    }
}

PlanCodePanel.propTypes = {
    onSelect: PropTypes.func.isRequired,
    brandId: PropTypes.string,
    dealerId: PropTypes.string,
    intl: PropTypes.object,
    materialGroupKDBOMCode: PropTypes.string,
    partOrderTypeId: PropTypes.string,
    transportType: PropTypes.number,
    onCancel: PropTypes.func,
};
import {injectIntl} from './intl';
export default injectIntl(PlanCodePanel);
